home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 17 / CU Amiga Magazine's Super CD-ROM 17 (1997)(EMAP Images)(GB)[!][issue 1997-12].iso / CUCD / Programming / DiceSource / lib / unix / mktemp.c < prev    next >
C/C++ Source or Header  |  1997-09-09  |  1KB  |  60 lines

  1. /*
  2.  *  unix/mktemp.c  - Contributed by Ben Jackson
  3.  */
  4.  
  5. #include <string.h>
  6. #include <sys/stat.h>
  7. #include <clib/exec_protos.h>
  8.  
  9. static const char base36[]= "01234567890abcdefghijklmnopqrstuvwxyz";
  10.  
  11. static char *itob36(unsigned long num)
  12. {
  13.     static char result[7];
  14.     int i;
  15.     char *ptr;
  16.  
  17.     result[6] = '\0';
  18.  
  19.     for(i = 5, ptr = result + i; i && num; i--, ptr--) {
  20.         *ptr = base36[num % 36];
  21.         num /= 36;
  22.     }
  23.     return ptr+1;
  24. }
  25.  
  26. char *mktemp(char *template)
  27. {
  28.     static unsigned long next = 0;
  29.     int n = 0, len = strlen(template);
  30.     unsigned long pid = (long)FindTask(NULL) * 36 * 36;
  31.     struct stat buf;
  32.     char *ptr;
  33.  
  34.     for(ptr = template + len - 1;'X' == *ptr; --ptr) ++n;
  35.     ++ptr;
  36.  
  37.     if(!n)
  38.         return NULL;  /* no trailing Xs */
  39.  
  40.     if(!strncmp(template, "/tmp/", 5)) {
  41.         /* amiga hack */
  42.         memcpy(template, "t:bjj", 5);
  43.     }
  44.  
  45.     /* this loop could be very bad if someone did something stupid,
  46.      * but UNIX will try 26^n files too.
  47.      */
  48.     do {
  49.         char *repl = itob36(pid + next++);
  50.         int l;
  51.  
  52.         l = strlen(repl);
  53.         if(l > n) repl += l - n;
  54.         strcpy(ptr, repl);
  55.     } while(!stat(template, &buf));
  56.  
  57.     return template;
  58. }
  59.  
  60.